package server.load;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.mapper.MappedContext;
import server.mapper.MappedHost;
import server.mapper.MappedWrapper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class LoaderServer {

    /**
     * 加载解析Server.xml,初始化映射关系组件
     */
    public List<MappedHost> load(){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = null;
        List<MappedHost> mappedHostList = new ArrayList<>();

        try {
            document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            //解析<Host>标签下的内容
            List<Element> hostNodes = rootElement.selectNodes("//Host");
            for (Element hostNode : hostNodes) {
                String hostName = hostNode.attributeValue("name");
                String appBase = hostNode.attributeValue("appBase");

                //解析<Context>标签下的内容
                List<MappedContext> mappedContextList = new ArrayList<>();
                List<Element> contextNodes = hostNode.selectNodes("//Context");
                for (Element contextNode : contextNodes) {
                    String docBase = contextNode.attributeValue("docBase");
                    String path = contextNode.attributeValue("path");

                    //读取<Context>下配置的项目中的 web.xml 文件内容
                    FileInputStream inputStream = new FileInputStream(appBase + docBase + "/web.xml");
                    LoadServlet loadServlet = new LoadServlet();
                    List<MappedWrapper> mappedWrapperList = loadServlet.load(appBase + docBase, inputStream);
                    MappedContext mappedContext = new MappedContext(path, docBase, mappedWrapperList);
                    mappedContextList.add(mappedContext);
                }

                MappedHost mappedHost = new MappedHost(hostName, appBase, mappedContextList);
                mappedHostList.add(mappedHost);
            }
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return mappedHostList;
    }
}
